package com.iaz.tech.tools.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileInputStream;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class FileTools {
    /**
	 * 存储文件（新建或者覆盖）
	 * @param fileNameWithPath
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static boolean saveFileData(String fileNameWithPath, String data) throws Exception {
		boolean result = false;
		if (UtilTools.IsNull(data) || UtilTools.IsNull(fileNameWithPath)) {
			return result;
		}
		try {
			File file = new File(fileNameWithPath);
			if (!file.exists()) {
				file.createNewFile();
			} else {

			}

			FileOutputStream out = new FileOutputStream(file, false);
			out.write(data.getBytes());
			out.flush();
			result = true;
			out.close();
			return result;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 追加模式
	 * @param fileNameWithPath
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static boolean saveFileData_append(String fileNameWithPath, String data) throws Exception {
		boolean result = false;
		if (UtilTools.IsNull(data) || UtilTools.IsNull(fileNameWithPath)) {
			return result;
		}
		try {
			File file = new File(fileNameWithPath);
			if (!file.exists()) {
				file.createNewFile();
			} else {

			}

			FileOutputStream out = new FileOutputStream(file, true);
			out.write(data.getBytes());
			out.flush();
			result = true;
			out.close();
			return result;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 获得Text 文件
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static String getTextFileData(File file) throws Exception{
		String result = "";

		if( file == null ) return result;
		if( !file.exists()) return result;
		if( file.isDirectory() ) return result;
		if( !file.isFile()) return result;
		BufferedReader bReader = null;
		try {
			FileReader reader = new FileReader(file);//定义一个fileReader对象，用来初始化BufferedReader
			bReader = new BufferedReader(reader);//new一个BufferedReader对象，将文件内容读取到缓存
			StringBuilder sb = new StringBuilder();//定义一个字符串缓存，将字符串存放缓存中
			String s = "";
			while ((s =bReader.readLine()) != null) {//逐行读取文件内容，不读取换行符和末尾的空格
				sb.append(s + "\n");//将读取的字符串添加换行符后累加存放在缓存中
			}

			bReader.close();
			result = sb.toString();
		}catch(Exception e){
			result = "";
			e.printStackTrace(System.out);
		}finally{
			try{
				if( bReader != null ){
					bReader.close();
				}

			}catch(Exception e){}
		}


		return result;
	}

	/**
	 * 读取文件, 带有附件
	 * @param fileNameWithPath
	 * @return
	 * @throws Exception
	 */
	public static String getFileData(String fileNameWithPath) throws Exception {
		String result = "";
		if (UtilTools.IsNull(fileNameWithPath)) {
			return result;
		}
		FileInputStream in = null;
		try {
			File file = new File(fileNameWithPath);
			if (!file.exists()) {
				return result;
			}

			in = new FileInputStream(file);
			StringBuffer sBuf = new StringBuffer();

			byte[] data = new byte[2000];
			memset(data, (byte) 0);

			int readCount = in.read(data);
			while (readCount != -1) {

				sBuf.append(new String(data));
				memset(data, (byte) 0);
				readCount = in.read(data);
			}
			result = sBuf.toString();
			return result;
		} catch (Exception e) {
			return "";
		} finally {
			if (in != null) {
				in.close();
			}
		}
	}

	/**
	 * 读取文件
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static String getFileData(File file) throws Exception {
		String result = "";
		if (file == null) {
			return result;
		}
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			StringBuffer sBuf = new StringBuffer();

			byte[] data = new byte[2000];
			memset(data, (byte) 0);

			int readCount = in.read(data);
			while (readCount != -1) {
				sBuf.append(new String(data));
				memset(data, (byte) 0);
				readCount = in.read(data);
			}
			result = sBuf.toString();
			return result;
		} catch (Exception e) {
			return "";
		} finally {
			if (in != null) {
				in.close();
			}
		}
	}

	public static void memset(byte[] data, byte ch) throws Exception {
		if (data == null) {
			return;
		}
		if (data.length == 0) {
			return;
		}
		for (int ii = 0; ii < data.length; ii++) {
			data[ii] = ch;
		}
	}

	/**
	 * 遍历目录，用于获得文件名
	 * @param directory
	 * @return
	 * @throws Exception
	 */
	public static Map<String,String> lstFilesWithoutExtend(String directory) throws Exception{
		Map<String,String> result = new HashMap<String,String>();

		if( UtilTools.IsNull( directory)) throw new Exception("路径名没有指定。");

		File file = new File( UtilTools.Trim( directory ) );
		if( !file.isDirectory() ){
			throw new Exception("入口参数：" + directory + "不是合法的路径。");
		}

		File[] children = file.listFiles();
		if( children == null ) return result;
		if( children.length == 0 ) return result;

		for(File _file : children){
			if( _file == null ) continue;
			if( _file.isDirectory() ) continue;
			if( !_file.exists() ) continue;
			if( !_file.isFile() ) continue;

			String file_single_name = UtilTools.Trim(  _file.getName() );

			int last_index = file_single_name.lastIndexOf( ".");
			String key = file_single_name;
			if( last_index >= 0 ){
				key = UtilTools.Trim( file_single_name.substring(0, last_index)   );
			}
			if( UtilTools.IsNull( key )) continue;
			String value = UtilTools.Trim( _file.getPath()  );
			result.put( key, value);
		}

		return result;
	}
	

	/**
	 * 遍历目录，用于获得文件名
	 * @param directory
	 * @return
	 * @throws Exception
	 */
	public static List<String> lstFiles(String directory) throws Exception{
		List<String> result = new ArrayList<>();

		if( UtilTools.IsNull( directory)) throw new Exception("路径名没有指定。");

		File file = new File( UtilTools.Trim( directory ) );
		if( !file.isDirectory() ){
			throw new Exception("入口参数：" + directory + "不是合法的路径。");
		}

		File[] children = file.listFiles();
		if( children == null ) return result;
		if( children.length == 0 ) return result;

		for(File _file : children){
			if( _file == null ) continue;
			if( _file.isDirectory() ) continue;
			if( !_file.exists() ) continue;
			if( !_file.isFile() ) continue;

			String file_single_name = UtilTools.Trim(  _file.getName() );

			result.add( file_single_name);
		}

		return result;
	}

	/**
	 * 遍历目录，用于获得文件名
	 * @param directory		所属目录及文件夹
	 * @param extend      	文件的扩展名
	 * @return
	 * @throws Exception
	 */
	public static List<String> lstFiles(String directory, String extend) throws Exception{
		List<String> result = new ArrayList<>();

		if( UtilTools.IsNull( directory)) throw new Exception("路径名没有指定。");

		File file = new File( UtilTools.Trim( directory ) );
		if( !file.isDirectory() ){
			throw new Exception("入口参数：" + directory + "不是合法的路径。");
		}
		if (UtilTools.IsNull(extend)) {
			throw new Exception("本方法仅仅支持extend是输入的。");
		}

		File[] children = file.listFiles();
		if( children == null ) return result;
		if( children.length == 0 ) return result;

		String tmp_extend = UtilTools.Trim(extend);

		for(File _file : children){
			if( _file == null ) continue;
			if( _file.isDirectory() ) continue;
			if( !_file.exists() ) continue;
			if( !_file.isFile() ) continue;

			String file_single_name = UtilTools.Trim(  _file.getName() );
			if (UtilTools.IsNull(file_single_name)) {
				continue;
			}

			int lastindex = file_single_name.lastIndexOf(".");
			if (lastindex <= 0){
				continue;
			}

			String extend_file = UtilTools.Trim(file_single_name.substring(lastindex + ".".length()));
			if (!extend_file.equalsIgnoreCase(tmp_extend)){
				continue;
			}
			result.add( file_single_name);
		}

		return result;
	}
	
	public static List<String> readFileLines( File file ) throws Exception{
		List<String> result = new ArrayList<String>();
		if( file == null ) return result;
		BufferedReader in = null;
		try {
			in = new BufferedReader(new FileReader(file));
			String str;
			while ((str = in.readLine()) != null) {
				if( UtilTools.IsNull(str )) continue;
				result.add( UtilTools.Trim(str) );
			}
		}catch (Exception e) {
			return new ArrayList<String>();
		}finally{
			try{
				if( in != null ){
					in.close();
				}
			}catch(Exception e){}
		}

		return result;
	}
}